/**
 * 
 */
package nguyen.hoan.sharelocation.service;

import nguyen.hoan.sharelocation.exception.MyNullPointerException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;

/**
 * @author Hoan Apr 5, 2014 3:16:52 PM
 * 
 */
public class MyGoogleMapService implements LocationListener {

	private static final long MIN_TIME = 400;
	private static final float MIN_DISTANCE = 1000;

	private GoogleMap googleMap;
	private LocationManager locationManager;

	public MyGoogleMapService(GoogleMap googleMap, LocationManager locationManager) {
		
		this.googleMap = googleMap;
		this.locationManager = locationManager;
	}

	public void settingMapUI() {

		if (googleMap != null) {
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);
			googleMap.getUiSettings().setZoomControlsEnabled(true);
			googleMap.getUiSettings().setCompassEnabled(true);
			googleMap.setMyLocationEnabled(true);
		} else {
			try {
				throw new MyNullPointerException();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public void bindLocationChangedListener() {
		
		if (locationManager != null) {
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
		} else {
			try {
				throw new MyNullPointerException();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onLocationChanged(Location location) {

		LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
		CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
		googleMap.animateCamera(cameraUpdate);
		locationManager.removeUpdates(this);
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

}
